package com.getword.utils.jsonserialize;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;

/**
 * 文章收藏的时间:
 * 今年：4月5日
 * 非今年：2014年4月5日
 */
public class ArticleCollectDateSerializer extends JsonSerializer<Date> {
    @Override
    public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value != null) {
            Calendar calendar = Calendar.getInstance();//日历对象
            calendar.setTime(value);//设置当前日期
            String result = "";
            LocalDate now = LocalDate.now();
            int year = calendar.get(Calendar.YEAR);
            // 月、日
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            if (now.getYear() == year) {
                result = month + "月" + day + "日";
            } else {
                result = year + "年" + month + "月" + day + "日";
            }
            gen.writeString(result);
        }
    }
}
